﻿var Category = {
    version: '1.0.0.0.0',
    ListCategory: [],
    ProductType: 1,
    ArticleType: 2
};

Category.Init = function () {
    $('#hfCategoryType').val(Category.ProductType);
    Category.BuildTree();
    Category.BuildTreeDropDownList("#ddlParentId", 0);
};

Category.BuildTree = function () {
    $('#listCategory tbody').html('');
    var typeId = $('#hfCategoryType').val();

    if (Category.ListCategory.length > 0) {
        _list(Category.ListCategory);
    }
    else {
        var url = String.format('/GetRequest.ashx?m=category&action=listtree&tId={0}&rand={1}', typeId, Math.random());
        $.getJSON(url, function (res) {
            if (res.Success) {
                if (res != null) {
                    Category.ListCategory = res;

                    _list(res);
                }
            }
        });
    }

    // List Tree
    function _list(result) {
        $.Mustache.load('/templates/category/list.htm')
            .done(function () {
                $('#listCategory tbody').mustache('tpl-category-list', result);
                $('form').jqTransform();
                $("#valid").validationEngine();
                $('.topDir').tipsy({ fade: true, gravity: 's' });
            });
    };
};

Category.BuildTreeDropDownList = function (ddlArea, selected) {
    var typeId = $('#hfCategoryType').val();

    if (Category.ListCategory.length > 0) {
        _dropdownlist(Category.ListCategory);
    }
    else {

        var url = String.format('/GetRequest.ashx?m=category&action=listtree&tId={0}&rand={1}', typeId, Math.random());
        $.getJSON(url, function (res) {
            if (res.Success) {
                if (res != null) {
                    Category.ListCategory = res;
                    _dropdownlist(res);
                }
            }
        });
    }

    // DropDownList
    _dropdownlist = function (result) {
        var html = '';
        html += '<select style="width: 200px">';

        if (result.Data.length > 0) {
            html += '<option value="0">-- Gốc --</option>';

            $.each(result.Data, function (i, val) {
                if (selected > 0 && val.CategoryId == selected)
                    html += String.format('<option value="{0}" selected="selected">{1}</option>', val.CategoryId, val.Name);
                else
                    html += String.format('<option value="{0}">{1}</option>', val.CategoryId, val.Name);
            });
        }
        else {
            html += '<option value="0">-- Gốc --</option>';
        }

        html += '</select>';

        $(ddlArea).html(html);
        $('form').jqTransform();
    };
};

Category.SelectedType = function () {
    var typeId;
    $.each($('#ddlTypeId ul li a'), function () {
        if ($(this).attr('class') == 'selected') {
            var index = $(this).attr('index');
            var value = $('#ddlTypeId select.jqTransformHidden option:eq(' + index + ')').attr('value');
            typeId = value;
        }
    });

    $('#hfCategoryType').val(typeId);
    Category.BuildTree();
    Category.Reset();
};

Category.GetCategory = function (id) {
    $('#toTop').click();
    var url = String.format('/GetRequest.ashx?m=category&action=getcategory&cId={0}&rand={1}', id, Math.random());
    $.getJSON(url, function (res) {
        if (res.Success) {
            if (res != null) {
                $('#listCategory table tr').removeClass('gradeC');
                $('.grade-' + id).addClass('gradeC');

                Category.BuildTreeDropDownList("#ddlParentId", res.Data.ParentId);
                $('#txtName').val(res.Data.Name);
                $('#txtPriority').val(res.Data.Priority);
                $('#txtImagePath').val(res.Data.ImagePath);

                $('#hfId').val(id); // Set Id to Hidden Field                
            }
        }
    });
};

Category.Reset = function () {
    $('#hfId').val(0);
    $('#txtName').val('');
    $('#txtPriority').val('');
    $('#txtImagePath').val('');
    Category.BuildTreeDropDownList("#ddlParentId", 0);
    $("#valid").validationEngine();
    $('.topDir').tipsy({ fade: true, gravity: 's' });
};

Category.Save = function () {
    var parentId;
    $.each($('#ddlParentId ul li a'), function () {
        if ($(this).attr('class') == 'selected') {
            var index = $(this).attr('index');
            var value = $('#ddlParentId select.jqTransformHidden option:eq(' + index + ')').attr('value');
            parentId = value;
        }
    });

    var typeId = $('#hfCategoryType').val();
    var id = $('#hfId').val();

    var url = String.format('/GetRequest.ashx?m=category&action=save&tId={0}&cId={1}&name={2}&pId={3}&priority={4}&imgPath={5}',
                                typeId, id, $('#txtName').val(), parentId, $('#txtPriority').val(), $('#txtImagePath').val());

    $.post(url, function () {
        if (id > 0) {
            $.jGrowl('Sửa danh mục thành công!', { header: 'Thông báo:' });
            $('#listCategory table tr').removeClass('gradeC');
            $('.c-' + id).addClass('gradeC');
        }
        else
            $.jGrowl('Tạo mới danh mục thành công!', { header: 'Thông báo:' });

        Category.BuildTree();

        Category.Reset();
    });
};

Category.SavePriority = function () {
    var count = 0;
    $.each($('#listCategory tbody tr'), function () {
        // Tách lấy Id
        var classVal = $(this).attr('class');
        var splitClass1 = classVal.split(' ');
        var splitClass2 = splitClass1[0].split('-');

        var id = splitClass2[1];
        var priority = $(this).find('input').val();

        if (id > 0 && priority > 0) {
            count++;
            var url = String.format('/GetRequest.ashx?m=category&action=savepriority&cId={0}&priority={1}', id, priority);
            $.getJSON(url, function (res) {
                if (res.Success) {

                }
            });
        }
    });
    if (count > 0) {
        $.jGrowl(String.format('Cập nhật độ ưu tiên thành công!'), { header: 'Thông báo:' });
        Category.BuildTree();
    }
};

Category.Delete = function (id) {
    $('#listCategory table tr').removeClass('gradeC');
    $('.c-' + id).addClass('gradeC');

    jConfirm('', 'Bạn có chắc chắn muốn xóa?', function (result) {
        if (result) {
            var url = String.format('/GetRequest.ashx?m=category&action=delete&cId={0}', id);
            $.post(url, function () { })
                .done(function () {
                    $.jGrowl(String.format('Xóa danh mục thành công!'), { header: 'Thông báo:' });
                    Category.BuildTree();
                });

            Category.Reset();
        }
    });
};